/**
 * @file ledcolor.cpp
 * @brief LED全局颜色控制类实现
 *
 * 提供独立的LED颜色控制，与峰值点颜色系统分离
 * 支持多种颜色方案：彩虹、火焰、海洋、森林、派对、单色
 */

#include "../include/ledcolor.h"
#include "../include/config.h"
#include "../include/i2sfft.h"
#include <Arduino.h>

// 静态成员初始化
LEDColorController *LEDColorController::instance_ = nullptr;

/**
 * @brief 构造函数
 */
LEDColorController::LEDColorController()
    : currentScheme_(COLOR_RAINBOW), singleColor_(CRGB::White), animationTime_(0), animationPhase_(0), animationSpeed_(200) // 提高默认速度：从128增加到200
      ,
      adjustedRainbowSpeed_(50) // 初始化调整后的彩虹速度为默认值
      ,
      saturation_(255) // 默认全饱和度
      ,
      lastUpdateTime_(0)
{
    Serial.println("[LED颜色] 全局颜色控制器初始化完成");
}

/**
 * @brief 获取单例实例
 */
LEDColorController &LEDColorController::instance()
{
    if (!instance_)
    {
        instance_ = new LEDColorController();
    }
    return *instance_;
}

/**
 * @brief 设置当前颜色方案
 */
void LEDColorController::setColorScheme(ColorScheme scheme)
{
    currentScheme_ = scheme;
    resetAnimation();
    Serial.printf("[LED颜色] 切换到颜色方案: %s\n", getColorSchemeName(scheme));
}

/**
 * @brief 更新动画效果
 */
void LEDColorController::update()
{
    uint32_t currentTime = millis();

    // 从配置中获取当前的速度设置（用于彩虹模式）
    uint8_t rainbowSpeed = g_config.rainbowSpeed;
    
    // 使用FFT节拍强度动态调整彩虹速度 - 优化版本
    float beatIntensity = getCurrentBeatSignal();
    if (beatIntensity > 0.0f) {
        // 优化1: 使用非线性映射，让节拍响应更自然
        float normalizedBeat = beatIntensity / g_config.beatBoostFactor; // 归一化到0-1
        float beatCurve = normalizedBeat * normalizedBeat; // 平方曲线，低强度变化更平缓
        
        // 优化2: 混合原始速度和节拍速度，而不是完全替换
        uint8_t baseBeatSpeed = map(beatCurve, 0.0f, 1.0f, rainbowSpeed, 100); // 从当前速度到最大值
        rainbowSpeed = (rainbowSpeed * 0.7f) + (baseBeatSpeed * 0.3f); // 70%原速度 + 30%节拍速度
        
        // 优化3: 限制变化幅度，避免过于激烈的跳跃
        rainbowSpeed = constrain(rainbowSpeed, g_config.rainbowSpeed * 0.8f, g_config.rainbowSpeed * 2.0f);
    } else {
        // 优化4: 没有节拍时，平滑回归到原始设置值
        float targetSpeed = g_config.rainbowSpeed;
        rainbowSpeed = (rainbowSpeed * 0.95f) + (targetSpeed * 0.05f); // 缓慢回归
    }

    // 保存调整后的速度供其他函数使用
    adjustedRainbowSpeed_ = rainbowSpeed;

    // 根据彩虹速度配置控制更新频率
    uint32_t updateInterval = map(rainbowSpeed, 1, 100, 100, 10);

    if (currentTime - lastUpdateTime_ >= updateInterval)
    {
        uint32_t deltaTime = currentTime - lastUpdateTime_;
        animationTime_ += deltaTime;

        // 根据速度设置调整相位变化步长
        uint8_t phaseStep = map(rainbowSpeed, 1, 100, 1, 8);
        animationPhase_ = (animationPhase_ + phaseStep) % 256;

        lastUpdateTime_ = currentTime;
    }
}

/**
 * @brief 获取颜色方案名称
 */
const char *LEDColorController::getColorSchemeName(ColorScheme scheme)
{
    const char *names[] = {"彩虹", "熔岩", "海洋", "森林", "派对", "云朵"};
    if (scheme < COLOR_COUNT)
        return names[scheme];
    return "未知";
}

/**
 * @brief 设置动画速度
 */
void LEDColorController::setAnimationSpeed(uint8_t speed)
{
    animationSpeed_ = speed;
    Serial.printf("[LED颜色] 设置动画速度: %d\n", speed);
}

/**
 * @brief 设置颜色饱和度
 */
void LEDColorController::setSaturation(uint8_t saturation)
{
    saturation_ = saturation;
    Serial.printf("[LED颜色] 设置饱和度: %d\n", saturation);
}

/**
 * @brief 重置动画相位
 */
void LEDColorController::resetAnimation()
{
    animationTime_ = 0;
    animationPhase_ = 0;
    lastUpdateTime_ = millis();
}

/**
 * @brief 火焰色实现 - 红橙黄渐变
 */
CRGB LEDColorController::getFireColor(float position, uint8_t brightness)
{
    // 火焰效果：底部红色，中间橙色，顶部黄色
    uint8_t hue;
    if (position < 0.3f)
    {
        hue = 0; // 红色
    }
    else if (position < 0.7f)
    {
        hue = 16; // 橙色
    }
    else
    {
        hue = 32; // 黄色
    }

    // 添加闪烁效果
    uint8_t flicker = sin8((animationTime_ / 20) + (position * 100));
    uint8_t adjustedBrightness = brightness * (200 + (flicker / 4)) / 255;

    return CHSV(hue, saturation_, adjustedBrightness);
}

/**
 * @brief 海洋色实现 - 蓝绿青渐变
 */
CRGB LEDColorController::getOceanColor(float position, uint8_t brightness)
{
    // 海洋效果：深蓝到浅蓝到青绿
    uint8_t hue = 160 + (position * 40); // 从深蓝(160)到青绿(200)

    // 添加波浪效果
    uint8_t wave = sin8((animationTime_ / 30) + (position * 150));
    hue += (wave / 8);

    return CHSV(hue, saturation_, brightness);
}

/**
 * @brief 森林色实现 - 绿色系渐变
 */
CRGB LEDColorController::getForestColor(float position, uint8_t brightness)
{
    // 森林效果：深绿到浅绿到黄绿
    uint8_t hue = 85 + (position * 25); // 从绿色(85)到黄绿(110)

    // 渐变饱和度效果
    uint8_t adjustedSaturation = saturation_ - (position * 50);
    if (adjustedSaturation < 128)
    {
        adjustedSaturation = 128; // 最低饱和度限制
    }

    // 添加微风效果
    uint8_t breeze = sin8((animationTime_ / 50) + (position * 80));
    hue += (breeze / 16);

    return CHSV(hue, adjustedSaturation, brightness);
}

/**
 * @brief 派对色实现 - 快速变化多彩
 */
CRGB LEDColorController::getPartyColor(float position, uint8_t brightness)
{
    // 派对效果：快速变化的鲜艳色彩，使用HSV色彩空间以获得更丰富的颜色
    // 结合使用动画相位和位置，创造出流动和闪烁的效果
    uint8_t hue = (animationPhase_ + (int)(position * 50)) % 255;

    // 使用Perlin噪声增加随机性，使颜色变化不那么线性
    uint8_t noise = inoise8(animationPhase_ * 2, (uint32_t)(position * 1000));
    if (noise > 180) // 随机闪烁白色
    {
        return CRGB(CRGB::White).nscale8(brightness);
    }

    // 饱和度保持最大，以获得鲜艳的颜色
    CRGB color = CHSV(hue, 255, 255);
    return color.nscale8(brightness);
}

/**
 * @brief 彩虹色实现 - 动态七彩渐变（支持扩展类型和方向）
 */

// 显式声明全局变量
extern uint8_t currentRainbowDirection;
extern bool colorRandomSwitch;

CRGB LEDColorController::getRainbowColor(float position, uint8_t brightness, int index, int totalCount)
{
    position = constrain(position, 0.0f, 1.0f);
    uint8_t rainbowType = g_config.rainbowType;
    uint8_t rainbowSpeed = adjustedRainbowSpeed_; // 使用update()函数中调整过的速度
    uint8_t rainbowSmooth = g_config.rainbowSmooth;
    uint8_t rainbowDirection = g_config.rainbowDirection;

    if (rainbowDirection == 0)
    {
        rainbowDirection = currentRainbowDirection; // 随机生成0-8的值
    }else{
        colorRandomSwitch = false;
        };

    // 动画速度因子计算
    float speedFactor = rainbowSpeed * 0.10f + 0.01f;
    uint32_t animTime = animationTime_ * speedFactor;
    uint8_t animPhase = animationPhase_ * speedFactor;
    float timeOffset = (float)animPhase / 255.0f;

    float pos = position;

    // 扩展方向名称实现
    switch (rainbowDirection)
    {

    case 0: // 波浪流动 - 按段数产生波浪效果
        if (totalCount > 0 && index >= 0)
        {
            colorRandomSwitch = true;
        }

    case 1: // 上-下 - 应用速度和平滑控制
    {
        // 应用速度控制
        float adjustedSpeedFactor = speedFactor * (rainbowSpeed / 50.0f);
        float flowingOffset = timeOffset * adjustedSpeedFactor;

        // 应用平滑度效果
        float smoothFactor = (float)rainbowSmooth / 100.0f;
        float finalPos = position;
        if (smoothFactor > 0.01f)
        {
            // 添加垂直方向的平滑波动
            float wavePhase = (animTime * 0.002f) + (position * 6.28f * 2.0f);
            float waveOffset = sinf(wavePhase) * smoothFactor * 0.05f;
            finalPos += waveOffset;
        }

        pos = fmod(finalPos + flowingOffset, 1.0f);
        if (pos < 0)
            pos += 1.0f;
    }
    break;
    case 2: // 下-上 - 应用速度和平滑控制
    {
        // 应用速度控制
        float adjustedSpeedFactor = speedFactor * (rainbowSpeed / 50.0f);
        float flowingOffset = timeOffset * adjustedSpeedFactor;

        // 应用平滑度效果
        float smoothFactor = (float)rainbowSmooth / 100.0f;
        float finalPos = 1.0f - position;
        if (smoothFactor > 0.01f)
        {
            // 添加垂直方向的平滑波动
            float wavePhase = (animTime * 0.002f) + (position * 6.28f * 2.0f);
            float waveOffset = sinf(wavePhase) * smoothFactor * 0.05f;
            finalPos += waveOffset;
        }

        pos = fmod(finalPos + flowingOffset, 1.0f);
        if (pos < 0)
            pos += 1.0f;
    }
    break;
    case 3: // 左-右 - 按段数流动
        if (totalCount > 0 && index >= 0)
        {
            // 根据LED在灯带中的段位置计算左右流动
            int segmentIndex = index; // index就是段索引
            float segmentPos = (float)segmentIndex / totalCount;
            pos = fmod(segmentPos + timeOffset, 1.0f);
        }
        else
        {
            pos = fmod(position + timeOffset, 1.0f);
        }
        break;
    case 4: // 右-左 - 按段数反向流动
        if (totalCount > 0 && index >= 0)
        {
            // 根据LED在灯带中的段位置计算右左流动
            int segmentIndex = index; // index就是段索引
            float segmentPos = (float)segmentIndex / totalCount;
            pos = fmod(1.0f - segmentPos + timeOffset, 1.0f);
        }
        else
        {
            pos = fmod(1.0f - position + timeOffset, 1.0f);
        }
        break;
    case 5: // 双向波纹 - 从两端向中心的波纹效果（平滑版）
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 25.0f); // 减慢基础速度
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float wavePhase = timeOffset * 6.28f * speedK;

            // 从左端开始的波纹 - 降低幅度
            float leftWave = sinf(segmentPos * 6.28f * 2.0f + wavePhase) * 0.12f; // 从0.25f降到0.12f

            // 从右端开始的波纹 - 降低幅度
            float rightWave = sinf((1.0f - segmentPos) * 6.28f * 2.0f + wavePhase + 3.14f) * 0.12f; // 从0.25f降到0.12f

            // 中心强化效果 - 更温和
            float centerEffect = expf(-6.0f * (segmentPos - 0.5f) * (segmentPos - 0.5f)) * smoothK * 0.08f; // 从0.15f降到0.08f

            pos = fmod(position + timeOffset * speedK * 0.6f + leftWave + rightWave + centerEffect, 1.0f); // 减慢整体流动
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + sinf(timeOffset * 4.0f) * 0.12f, 1.0f); // 降低备用算法幅度
        }
        break;
    case 6: // 脉冲波群 - 多个脉冲波沿灯带传播（平滑版）
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 20.0f); // 减慢基础速度
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.005f * speedK; // 减慢时间相位变化

            // 主脉冲波：大波包 - 降低幅度
            float mainPulse = sinf(segmentPos * 6.28f * 1.2f - timePhase) * 0.15f; // 从0.3f降到0.15f

            // 次脉冲波：小波包，频率不同 - 降低幅度
            float subPulse = sinf(segmentPos * 6.28f * 3.0f - timePhase * 1.4f) * smoothK * 0.10f; // 从0.2f降到0.10f

            // 群速度调制：让波群有包络效果 - 更温和
            float groupMod = cosf(segmentPos * 6.28f * 0.6f - timePhase * 0.4f) * smoothK * 0.08f; // 从0.15f降到0.08f

            pos = fmod(position + timeOffset * speedK * 0.8f + mainPulse + subPulse + groupMod, 1.0f); // 减慢整体流动
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + sinf(timeOffset * 4.0f) * 0.15f, 1.0f); // 降低备用算法幅度
        }
        break;
    case 7: // 环形流动 - 极光扫描风格的冷色环形效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 20.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float ringPos = (float)index / totalCount;
            float timePhase = animTime * 0.006f * speedK;

            // 主极光束：缓慢移动的冷色光束
            float beamCenter = fmod(timePhase * 0.8f, 1.0f);
            float distToBeam = fabsf(ringPos - beamCenter);
            if (distToBeam > 0.5f)
                distToBeam = 1.0f - distToBeam; // 环形距离处理

            // 光束宽度：呼吸式变化
            float beamWidth = 0.2f + sinf(timePhase * 0.3f) * 0.08f;

            // 极光强度：高斯分布的光束强度
            float auroraIntensity = 0.0f;
            if (distToBeam < beamWidth)
            {
                float normalized = distToBeam / beamWidth;
                auroraIntensity = expf(-3.0f * normalized * normalized); // 高斯分布
            }

            // 次极光束：反向移动的较小光束
            float subBeamCenter = fmod(-timePhase * 0.5f + 0.3f, 1.0f);
            float distToSubBeam = fabsf(ringPos - subBeamCenter);
            if (distToSubBeam > 0.5f)
                distToSubBeam = 1.0f - distToSubBeam;

            float subAuroraIntensity = 0.0f;
            if (distToSubBeam < beamWidth * 0.6f)
            {
                float subNormalized = distToSubBeam / (beamWidth * 0.6f);
                subAuroraIntensity = expf(-4.0f * subNormalized * subNormalized) * 0.7f;
            }

            // 环形波动：增加动态感
            float ringWave = sinf(ringPos * 6.28f * 3.0f + timePhase) * smoothK * 0.12f;

            // 冷色相位偏移：专门设计的冷色循环
            float coldColorPhase = auroraIntensity * 0.4f + subAuroraIntensity * 0.3f + ringWave;

            // 基础位置偏移
            pos = fmod(position + timeOffset * speedK * 0.7f + coldColorPhase, 1.0f);
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            // 备用算法：简单冷色环形流动
            pos = fmod(position + timeOffset * 1.5f, 1.0f);
        }
        break;
    case 8: // 螺旋波纹 - 螺旋式传播的波纹效果（平滑版）
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 22.0f); // 进一步减慢基础速度
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.004f * speedK; // 减慢时间相位变化

            // 螺旋波：主要的螺旋传播效果 - 大幅降低幅度
            float spiralWave = sinf(segmentPos * 6.28f * 2.0f - timePhase) * 0.14f; // 从0.28f降到0.14f

            // 反向螺旋：增加复杂度 - 降低幅度
            float counterSpiral = sinf(segmentPos * 6.28f * 1.5f + timePhase * 0.6f) * smoothK * 0.09f; // 从0.18f降到0.09f

            // 径向调制：让螺旋有径向变化 - 更温和
            float radialMod = cosf(segmentPos * 6.28f * 0.5f - timePhase * 0.25f) * smoothK * 0.06f; // 从0.12f降到0.06f

            // 整体旋转偏移 - 减缓
            float rotationOffset = timePhase * 0.5f; // 从0.8f降到0.5f

            pos = fmod(position + rotationOffset + spiralWave + counterSpiral + radialMod, 1.0f);
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + sinf(timeOffset * 3.0f) * 0.14f, 1.0f); // 降低备用算法幅度
        }
        break;
    case 9: // 干涉波纹 - 多点波源的干涉效果（平滑版）
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 20.0f); // 减慢基础速度
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.005f * speedK; // 减慢时间相位变化

            // 波源1：位置在0.25处 - 降低幅度
            float source1Dist = fabsf(segmentPos - 0.25f);
            float wave1 = sinf(source1Dist * 6.28f * 6.0f - timePhase) * 0.10f; // 从0.2f降到0.10f

            // 波源2：位置在0.75处 - 降低幅度
            float source2Dist = fabsf(segmentPos - 0.75f);
            float wave2 = sinf(source2Dist * 6.28f * 6.0f - timePhase + 1.57f) * 0.10f; // 从0.2f降到0.10f

            // 中心波源：增加复杂度 - 更温和
            float centerDist = fabsf(segmentPos - 0.5f);
            float centerWave = sinf(centerDist * 6.28f * 9.0f - timePhase * 1.2f) * smoothK * 0.08f; // 从0.15f降到0.08f

            // 干涉调制：模拟波的叠加效果 - 降低强度
            float interference = (wave1 + wave2 + centerWave) * smoothK * 0.8f; // 添加额外的0.8f衰减

            pos = fmod(position + timeOffset * speedK * 0.7f + interference, 1.0f); // 减慢整体流动
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + sinf(timeOffset * 3.0f) * 0.10f, 1.0f); // 降低备用算法幅度
        }
        break;

    case 10: // 音乐脉动 - 随音乐节奏脉动的彩虹效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 18.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.004f * speedK;

            // 使用节拍信号调制波动强度
            float beatIntensity = getCurrentBeatSignal();
            float beatFactor = 0.1f + (beatIntensity / g_config.beatBoostFactor) * 0.3f;

            // 主波动效果
            float mainWave = sinf(segmentPos * 6.28f * 2.5f - timePhase) * beatFactor;
            
            // 次波动效果
            float subWave = sinf(segmentPos * 6.28f * 4.0f + timePhase * 0.7f) * smoothK * beatFactor * 0.6f;
            
            // 整体流动
            pos = fmod(position + timeOffset * speedK * 0.6f + mainWave + subWave, 1.0f);
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + timeOffset + sinf(timeOffset * 4.0f) * 0.15f, 1.0f);
        }
        break;
    case 11: // 星光闪烁 - 随机闪烁的星星效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 25.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.003f * speedK;
            
            // 基础流动
            float baseFlow = fmod(segmentPos + timeOffset * speedK * 0.5f, 1.0f);
            
            // 随机闪烁效果
            uint16_t noiseVal = inoise16(index * 3000, animTime * 10);
            float flickerChance = (float)noiseVal / 65535.0f;
            
            // 闪烁概率随平滑度增加
            float flickerThreshold = 0.7f - smoothK * 0.3f;
            
            if (flickerChance > flickerThreshold)
            {
                // 闪烁时的颜色偏移
                float flickerIntensity = (flickerChance - flickerThreshold) / (1.0f - flickerThreshold);
                float flickerOffset = flickerIntensity * 0.3f;
                pos = fmod(baseFlow + flickerOffset, 1.0f);
            }
            else
            {
                pos = baseFlow;
            }
        }
        else
        {
            pos = fmod(position + timeOffset, 1.0f);
        }
        break;
    case 12: // 彩虹瀑布 - 从上到下流动的彩虹瀑布效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 20.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.005f * speedK;
            
            // 瀑布主流动效果
            float fallEffect = fmod(segmentPos + timePhase * 1.2f, 1.0f);
            
            // 水花飞溅效果
            float splashWave = 0.0f;
            if (segmentPos > 0.85f) // 底部区域产生水花
            {
                float bottomPos = (segmentPos - 0.85f) / 0.15f; // 归一化底部位置
                splashWave = sinf(bottomPos * 6.28f * 3.0f + timePhase * 2.0f) * smoothK * 0.15f;
            }
            
            // 水流波动
            float flowWave = sinf(segmentPos * 6.28f * 2.0f - timePhase * 0.8f) * smoothK * 0.08f;
            
            pos = fmod(fallEffect + splashWave + flowWave, 1.0f);
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + timeOffset * 1.2f, 1.0f);
        }
        break;
    case 13: // 彩虹螺旋 - 双向螺旋彩虹效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 22.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.003f * speedK;
            
            // 将灯带分为两部分，左右两侧
            float normalizedPos;
            if (segmentPos < 0.5f) {
                // 左侧 - 从中心向左螺旋
                normalizedPos = 1.0f - (segmentPos * 2.0f); // 1.0到0.0
                // 向左旋转
                float spiralEffect = timePhase * 1.2f;
                // 波浪效果
                float waveEffect = sinf(normalizedPos * 6.28f * 2.0f + timePhase * 2.0f) * smoothK * 0.15f;
                pos = fmod(normalizedPos + spiralEffect + waveEffect, 1.0f);
            } else {
                // 右侧 - 从中心向右螺旋
                normalizedPos = (segmentPos - 0.5f) * 2.0f; // 0.0到1.0
                // 向右旋转（反方向）
                float spiralEffect = -timePhase * 1.2f;
                // 波浪效果
                float waveEffect = sinf(normalizedPos * 6.28f * 2.0f - timePhase * 2.0f) * smoothK * 0.15f;
                pos = fmod(normalizedPos + spiralEffect + waveEffect, 1.0f);
            }
            
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + timeOffset, 1.0f);
        }
        break;
    case 14: // 彩虹脉搏 - 心跳式的彩虹脉动效果
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 20.0f);
            float smoothK = (float)rainbowSmooth / 100.0f;

            float segmentPos = (float)index / totalCount;
            float timePhase = animTime * 0.003f * speedK;
            
            // 心跳脉搏效果 - 模拟ECG波形
            float pulsePhase = fmod(timePhase, 1.0f);
            float pulseIntensity = 0.0f;
            
            // 创建心跳波形
            if (pulsePhase < 0.1f) // 第一个峰
                pulseIntensity = sinf(pulsePhase * 31.4f) * 0.15f;
            else if (pulsePhase < 0.2f) // 第二个峰
                pulseIntensity = sinf((pulsePhase - 0.1f) * 31.4f) * 0.25f;
            else if (pulsePhase < 0.4f) // 恢复期
                pulseIntensity = sinf((pulsePhase - 0.2f) * 15.7f - 1.57f) * 0.05f;
            
            // 脉搏传播效果
            float distFromCenter = fabsf(segmentPos - 0.5f) * 2.0f;
            float propagationDelay = distFromCenter * 0.2f; // 从中心向两边传播的延迟
            float adjustedPulsePhase = fmod(pulsePhase - propagationDelay, 1.0f);
            
            if (adjustedPulsePhase < 0.0f)
                adjustedPulsePhase += 1.0f;
                
            float adjustedPulseIntensity = 0.0f;
            if (adjustedPulsePhase < 0.1f)
                adjustedPulseIntensity = sinf(adjustedPulsePhase * 31.4f) * 0.15f;
            else if (adjustedPulsePhase < 0.2f)
                adjustedPulseIntensity = sinf((adjustedPulsePhase - 0.1f) * 31.4f) * 0.25f;
            else if (adjustedPulsePhase < 0.4f)
                adjustedPulseIntensity = sinf((adjustedPulsePhase - 0.2f) * 15.7f - 1.57f) * 0.05f;
            
            // 应用平滑度
            adjustedPulseIntensity *= (0.5f + smoothK * 0.5f);
            
            pos = fmod(segmentPos + timeOffset * speedK * 0.4f + adjustedPulseIntensity, 1.0f);
            if (pos < 0)
                pos += 1.0f;
        }
        else
        {
            pos = fmod(position + timeOffset + sinf(timeOffset * 6.0f) * 0.1f, 1.0f);
        }
        break;
    case 15: // 蓝紫双向渐变效果 - 自上而下
        if (totalCount > 0 && index >= 0)
        {
            float speedK = speedFactor * (rainbowSpeed / 24.0f);
            
            // 确保使用Y坐标实现自上而下的渐变
            // 假设LED排列是从上到下的，使用索引位置
            float segmentPos = (float)index / totalCount;
            
            // 添加时间偏移使渐变有流动感
            float timePhase = animTime * 0.002f * speedK;
            
            // 将位置映射到0-1之间，并添加时间偏移
            float basePos = fmod(segmentPos + timePhase, 1.0f);
            
            // 创建双向渐变效果（从蓝到紫再到蓝）
            // 使用正弦函数将0-1的范围映射为双向变化
            // sin(x*PI)在0-1范围内从0到1再到0
            float oscillation = sinf(basePos * 3.14159f);
            
            // 将oscillation从0-1映射到蓝色和紫色之间(0.55-0.85)
            pos = 0.55f + oscillation * 0.3f;
            
            if (pos < 0)
                pos += 1.0f;
            if (pos > 1.0f)
                pos -= 1.0f;
        }
        else
        {
            pos = fmod(position + timeOffset, 1.0f);
            // 创建双向渐变效果
            float oscillation = sinf(pos * 3.14159f);
            pos = 0.55f + oscillation * 0.3f;
        }
        break;

    default:
        pos = fmod(position + timeOffset, 1.0f);
        break;
    }

    // 扩展类型名称实现
    uint8_t hueBase = 0, hueRange = 255;
    uint8_t saturationAdjust = 255;

    // 特殊处理：环形流动模式强制使用冷色循环
    if (rainbowDirection == 6)
    {
        // 环形流动专用冷色循环：青色->蓝色->紫色->青色
        hueBase = 128;          // 从青色开始
        hueRange = 85;          // 覆盖青-蓝-紫范围
        saturationAdjust = 255; // 保持高饱和度以突出冷色效果
    }
    else
    {
        switch (rainbowType)
        {
        case 0: // 全彩
            hueBase = 0;
            hueRange = 255;
            saturationAdjust = 255;
            break;

        case 1:            // 冷色 (蓝、青、紫色系)
            hueBase = 128; // 从青色开始
            hueRange = 85; // 覆盖青-蓝-紫范围
            saturationAdjust = 240;
            break;

        case 2:            // 暖色 (红、橙、黄色系)
            hueBase = 0;   // 从红色开始
            hueRange = 64; // 覆盖红-橙-黄范围
            saturationAdjust = 255;
            break;

        default:
            hueBase = 0;
            hueRange = 255;
            saturationAdjust = 255;
            break;
        }
    }

    // 计算最终色调
    float normPos = fmod(pos, 1.0f);
    if (normPos < 0)
        normPos += 1.0f;

    uint8_t baseHue = hueBase + (uint8_t)(normPos * hueRange);

    // 平滑度效果 - 添加微妙的波动
    float smoothFactor = (float)rainbowSmooth / 100.0f;
    if (smoothFactor > 0.01f)
    {
        uint8_t waveAmplitude = (uint8_t)(smoothFactor * 20);      // 波动幅度
        uint16_t waveSpeed = 100 + (uint16_t)(smoothFactor * 300); // 波动速度
        uint8_t waveOffset = sin8((uint16_t)(animTime / 3 + normPos * waveSpeed));
        waveOffset = scale8(waveOffset, waveAmplitude);
        baseHue = baseHue + waveOffset;
    }

    // 应用饱和度调整
    uint8_t finalSaturation = scale8(saturationAdjust, saturation_);

    return CHSV(baseHue, finalSaturation, brightness);
}

/**
 * @brief 获取指定方案的颜色（带索引和总数参数）
 */
CRGB LEDColorController::getColorForPosition(float position, uint8_t brightness, int index, int totalCount)
{
    return getColorForPosition(position, currentScheme_, brightness, index, totalCount);
}

CRGB LEDColorController::getColorForPosition(float position, ColorScheme scheme, uint8_t brightness, int index, int totalCount)
{
    position = constrain(position, 0.0f, 1.0f);
    switch (scheme)
    {
    case COLOR_RAINBOW:
        return getRainbowColor(position, brightness, index, totalCount);
    case COLOR_FIRE:
        return getFireColor(position, brightness);
    case COLOR_OCEAN:
        return getOceanColor(position, brightness);
    case COLOR_FOREST:
        return getForestColor(position, brightness);
    case COLOR_PARTY:
        return getPartyColor(position, brightness);
    case COLOR_SINGLE:
        return singleColor_.nscale8(brightness);
    }
    return CRGB::Black; // 添加默认返回值以修复编译器警告
}

/**
 * @brief 云朵色实现 - 白色和淡蓝色的柔和过渡
 */
CRGB LEDColorController::getCloudColor(float position, uint8_t brightness)
{
    // 云朵效果：白色到淡蓝色的渐变
    uint8_t whiteLevel = 255 - (position * 255); // 从白到淡蓝
    uint8_t blueLevel = position * 255;          // 从蓝到淡蓝

    return CRGB(whiteLevel, whiteLevel, blueLevel).nscale8(brightness);
}

// ==================== 全局函数接口实现 ====================

/**
 * @brief 设置全局颜色方案
 */
void setGlobalColorScheme(uint8_t scheme)
{
    if (scheme < COLOR_COUNT)
        LEDColorController::instance().setColorScheme((ColorScheme)scheme);
}

/**
 * @brief 获取当前全局颜色方案
 */
uint8_t getCurrentGlobalColorScheme()
{
    return (uint8_t)LEDColorController::instance().getCurrentColorScheme();
}

/**
 * @brief 获取全局颜色（指定位置）
 */
CRGB getGlobalColorForPosition(float position, uint8_t brightness)
{
    return LEDColorController::instance().getColorForPosition(position, brightness);
}

/**
 * @brief 设置全局单色
 */
void setGlobalSingleColor(CRGB color)
{
    LEDColorController::instance().setSingleColor(color);
}

/**
 * @brief 获取全局颜色方案名称
 */
const char *getGlobalColorSchemeName(uint8_t scheme)
{
    return LEDColorController::getColorSchemeName((ColorScheme)scheme);
}

// 确保文件结束符正确
